package org.lql.algo.codecrush.hot100.stack;

import java.util.Stack;

/**
 * @author: liangqinglong
 * @date: 2025-10-14 16:28
 * @description: 394. 字符串解码 <a href="https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class DecodeString {

	public String decodeString(String s) {
		Stack<Integer> numStack = new Stack<>();
		Stack<StringBuilder> strStack = new Stack<>();
		StringBuilder str = new StringBuilder();
		int count = 0;
		for (char c : s.toCharArray()) {
			if (Character.isDigit(c)) {
				count = count * 10 + c - '0';
			} else if (c == '[') {
				numStack.push(count);
				count = 0;
				strStack.push(str);
				str = new StringBuilder();
			} else if (c == ']') {
				Integer tot = numStack.pop();
				StringBuilder tmp = strStack.pop();
				for (Integer i = 0; i < tot; i++) {
					tmp.append(str);
				}
				str = tmp;
			} else {
				str.append(c);
			}
		}
		return str.toString();
	}

	public static void main(String[] args) {
		DecodeString decodeString = new DecodeString();
		// aaabcbc
		System.out.println(decodeString.decodeString("3[a]2[bc]"));
		// accaccacc
		System.out.println(decodeString.decodeString("3[a2[c]]"));
		// abcabccdcdcdef
		System.out.println(decodeString.decodeString("2[abc]3[cd]ef"));
		// abccdcdcdxyz
		System.out.println(decodeString.decodeString("abc3[cd]xyz"));
	}
}
